package com.jeecg.demo.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.jdbc.support.incrementer.AbstractColumnMaxValueIncrementer;

/**
 * 表生成器模式最大序列值增量器
 */
public class TableGeneratorSequenceMaxValueIncrementer extends AbstractColumnMaxValueIncrementer {
	
	/** The next id to serve */
	private long nextId = 0;
	/** The max id to serve */
	private long maxId = 0;
	
	private String pkColumnValue;
	private String pkColumnName;
	private String valueColumnName;
	private Integer initialValue;
	private Integer allocationSize;
	
	/**
	 * Default constructor for bean property style usage.
	 * @see #setDataSource
	 * @see #setIncrementerName
	 */
	public TableGeneratorSequenceMaxValueIncrementer() {
	}

	/**
	 * Convenience constructor.
	 * @param dataSource the DataSource to use
	 * @param incrementerName the name of the sequence/table to use
	 */
	public TableGeneratorSequenceMaxValueIncrementer(DataSource dataSource, String incrementerName, String columnName) {
		super(dataSource, incrementerName, columnName);
	}
	
	/**
	 * 初始化表生成器模式最大序列值增量器
	 * @param dataSource 数据源
	 * @param incrementerName 增量器名称(增量表明)
	 * @param incrementerName 
	 * @param pkColumnValue 保存主键名字的字段
	 * @param pkColumnName 保存主键列名的列名
	 * @param valueColumnName 保存主键值的列名
	 * @param initialValue 初始化值
	 * @param allocationSize 自动增长值
	 */
	public TableGeneratorSequenceMaxValueIncrementer(DataSource dataSource, String incrementerName,
			String pkColumnValue, String pkColumnName, String valueColumnName, 
			Integer initialValue, Integer allocationSize) {
		super(dataSource, incrementerName, pkColumnValue);
		
		this.pkColumnValue = pkColumnValue;
		this.pkColumnName = pkColumnName;
		this.valueColumnName = valueColumnName;
		this.initialValue = initialValue;
		this.allocationSize = allocationSize;
	}

	@Override
	protected synchronized long getNextKey() throws DataAccessException {
		if (this.maxId == this.nextId) {
			Connection con = DataSourceUtils.getConnection(getDataSource());
			Statement stmt = null;
			try {
				stmt = con.createStatement();
				DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());

				int rsu = stmt.executeUpdate(String.format("UPDATE %S SET %S=%S+%S WHERE %S = '%S'", 
						this.getIncrementerName(), this.valueColumnName, this.valueColumnName, 
						this.allocationSize, this.pkColumnName, this.pkColumnValue));

				if (rsu == 0) {
					stmt.executeUpdate(String.format("INSERT INTO %S VALUES('%S', %S, sysdate)", 
							this.getIncrementerName(), this.pkColumnValue, this.initialValue));
				}
				
				ResultSet rs = stmt.executeQuery(String.format("SELECT %S FROM %S WHERE %S = '%S'", 
						this.valueColumnName, this.getIncrementerName(), this.pkColumnName, this.pkColumnValue));
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("last insert id failed after executing an update");
					}
					this.maxId = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
				this.nextId = this.maxId - getCacheSize() + 1;
			}
			catch (SQLException ex) {
				throw new DataAccessResourceFailureException("Could not obtain last insert id", ex);
			}
			finally {
				JdbcUtils.closeStatement(stmt);
				DataSourceUtils.releaseConnection(con, getDataSource());
			}
		}
		else {
			this.nextId++;
		}
		return this.nextId;
	}
}